package com.weipeep.common.utils.httpclient.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import com.weipeep.common.utils.httpclient.HttpRequest;
import com.weipeep.common.utils.httpclient.HttpRequest.Method;
import com.weipeep.common.utils.httpclient.HttpResponse;
import com.weipeep.common.utils.httpclient.HttpService;
import com.weipeep.common.utils.httpclient.OkHttpClientService;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

public class OKHttpUtil {
	private static int scnt = 3;
	private static HttpService []services =  new HttpService[scnt];
	private static AtomicInteger aint = new AtomicInteger();
	static{
		for (int i = 0; i < scnt; i++) {
			services[i]= new OkHttpClientService();
		}
	}
	
	public static HttpService getHttpClient(){
		int index = aint.getAndIncrement() % scnt;
		if(index < 0){
			aint.set(0);
			index = 0;
		} 
		return services[index];
	}
	
	public static Map<String, Object> get(String url, Map<String, String> params){
		return get(url +"?"+ toString(params));
	}
	
	public static Map<String, Object> get(String url){
		return get(url, "UTF-8");
	}
	
	public static Map<String, Object> get(String url, String charset, Map<String, String> params){
		return get(url+ "?"+toString(params), charset);
	}
	
	public static Map<String, Object> get(String url, String charset){
		return (Map<String, Object>) deserialize(getStr(url, charset));
	}
	
	public static String getStr(String url, String charset){
		HttpResponse res = null;
		try {
			res = request(url, charset);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(res == null) return "{\"state\":\"503\",\"msg\":\"http超时\"}";
		return res.getResponseString(charset);
	}
	
	public static HttpResponse request(HttpRequest request) throws Exception{
		return getHttpClient().execute(request);
	}
	
	public static HttpResponse request(String url, String charset) throws Exception{
		HttpRequest request = new HttpRequest(url, Method.get);
		request.setCharset(charset);
		return request(request);
	}
	
	public static Map<String, Object> uploadMultipart(String url, Map<String, File> params){
		HttpRequest request = new HttpRequest(url, Method.post);
		request.setFileMap(params);
		request.setCharset("UTF-8");
		try {
			String res = request(request).getResponseString("UTF-8");
			return (Map<String, Object>) deserialize(res);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static Map<String, Object> uploadByBody(String url, File file){
		HttpRequest request = new HttpRequest(url, Method.post);
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		try {
			IOUtil.copy(new FileInputStream(file), out);
			request.setRequestBody(out.toByteArray());
			request.setCharset("UTF-8");
			String res = request(request).getResponseString("UTF-8");
			return (Map<String, Object>) deserialize(res);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static String postStr(String url,String charset, Map<String, String> params){
		HttpRequest request = new HttpRequest(url, Method.post);
		request.setPostParams(params);
		request.setCharset(charset);
		try {
			return request(request).getResponseString(charset);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static Map<String, Object> post(String url, Map<String, String> params){
		String res = postStr(url, "UTF-8", params);
		return (Map<String, Object>) deserialize(res);
	}
	
	public static Object deserialize(String str){
		return JSON.parseObject(str, HashMap.class);
	}
	
	public static String serialize(Object obj){
		return JSON.toJSONString(obj, SerializerFeature.DisableCircularReferenceDetect, SerializerFeature.WriteMapNullValue,SerializerFeature.WriteNullStringAsEmpty,
					SerializerFeature.WriteDateUseDateFormat,SerializerFeature.WriteNullListAsEmpty);
	}
	
	public static String encode(String url) {
		try {
			return URLEncoder.encode(url, "utf8");
		} catch (Exception e) {
			return "";
		}
	}
	
	public static String toString(Map<String, String> params){
		StringBuffer buffer = new StringBuffer();
		for(String key: params.keySet()){
			if(buffer.length()>0){
				buffer.append("&");
			}
			buffer.append(key).append("=").append(encode(params.get(key)));
		}
		return buffer.toString();
	}

}
